package com.zlq.cn.util;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import com.aliyuncs.utils.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.Key;

public class KeyUtil {
    public static final String DefaultEightKey = "W%x^9981";
    public static final String ALGORITHM_DES = "DES/CBC/PKCS5Padding";
    public static final String ALGORITHM_AES = "AES/CBC/PKCS5Padding";
    public static String EncryptMode_Ecb = "ECB";
    public static String EncryptMode_Cbc = "CBC";

    /**
     * DES算法，对称解密
     *
     * @param data 待解密字符串
     * @param key  解密私钥，长度不能够小于8位
     * @return 解密后的字节数组
     * @throws Exception 异常
     */
    public static String decode(String key, String data) {
        if (data == null) {
            return null;
        }
        try {
            DESKeySpec dks = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            //key的长度不能够小于8位字节
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(DefaultEightKey.getBytes()));
            return new String(cipher.doFinal(hex2byte(data.getBytes())));
        } catch (Exception e) {
            e.printStackTrace();
            return data;
        }
    }

    /**
     * 二行制转字符串
     *
     * @param b
     * @return
     */
    private static String byte2hex(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                hs.append('0');
            }
            hs.append(stmp);
        }
        return hs.toString().toUpperCase();
    }

    private static byte[] hex2byte(byte[] b) {
        if ((b.length % 2) != 0) {
            throw new IllegalArgumentException();
        }
        byte[] b2 = new byte[b.length / 2];
        for (int n = 0; n < b.length; n += 2) {
            String item = new String(b, n, 2);
            b2[n / 2] = (byte) Integer.parseInt(item, 16);
        }
        return b2;
    }


    /**
     * AES对称高级加密
     *
     * @param plaintext   明文
     * @param Key         密钥
     * @param EncryptMode AES加密模式，CBC或ECB
     * @return 该字符串的AES密文值
     */
    public static String AES_Encrypt(Object plaintext, String Key, String EncryptMode) {
        String content = null;
        try {
            content = plaintext.toString();
            if (StringUtils.isEmpty(Key)) {
                return null;
            }
            byte[] raw = Key.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/" + EncryptMode + "/PKCS5Padding");
            if (EncryptMode.equalsIgnoreCase("ECB")) {
                cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            } else {
                //使用CBC模式，需要一个向量iv，可增加加密算法的强度
                IvParameterSpec iv = new IvParameterSpec(Key.getBytes("utf-8"));
                cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            }
            byte[] encrypted = cipher.doFinal(content.getBytes("utf-8"));
            return Base64.encode(encrypted);
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }

    /**
     * AES对称高级解密
     *
     * @param cipertext   密文
     * @param Key         密钥
     * @param EncryptMode AES加密模式，CBC或ECB
     * @return 该密文的明文
     */
    public static String AES_Decrypt(Object cipertext, String Key, String EncryptMode) {
        String CipherText = null;
        try {
            CipherText = cipertext.toString();
            if (StringUtils.isEmpty(Key)) {
                return null;
            }
            byte[] raw = Key.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/" + EncryptMode + "/PKCS5Padding");
            if (EncryptMode.equals("ECB")) {
                cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            } else {
                //使用CBC模式，需要一个向量iv，可增加加密算法的强度
                IvParameterSpec iv = new IvParameterSpec(Key.getBytes(StandardCharsets.UTF_8));
                cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            }
            byte[] encrypted1 = Base64.decode(CipherText);//先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted1);
                return new String(original, StandardCharsets.UTF_8);
            } catch (Exception e) {
                return null;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }

    }

    public static void main(String[] args) throws IOException {
        String content = "IUJc48xQs668mSGhyZOKReUHISuS/K2R9Kl3pgf5U0izmdbxeYN0VSpmYbCugKY4/OtwgyLSyaD/h2aXcYxCzhi5tkHpbYkajShkMeJ5/Jrxpkd4UZYImpL158TV0iwq9RKGsGqc4NSE1NWkFlbaq3wmhK4KqIDf7AXDqVKz694wFsTn9oMT4bK6z3HclNVZxljqGh8wDXgT3mlnm0artEOoV6JadveB0cm5r42kUC2i2PbCxBkoQTajgMf7ugwo0Znw9qTYS1mzpiQvR0c8I8TK8K6WVtytS/sI8N7gcZ5l6sOxLgD/n0gsdyKbgmsG";
        System.out.println("解密:" + KeyUtil.AES_Decrypt(content, "6f66a72e1c8462efa4adbcbd528bfb34", KeyUtil.EncryptMode_Ecb));

        String s = AES_Decrypt(FileUtil.readString(new File("C:\\Users\\14988\\Desktop\\分类.txt"), "UTF-8"), "6f66a72e1c8462efa4adbcbd528bfb34", KeyUtil.EncryptMode_Ecb);
        System.out.println(s);

    }
}
